using Mes.采购管理.model;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;

// 在文件顶部添加对login类的引用
using Mes;
using System.Net.Http;

namespace Mes.采购管理
{
    public partial class Revise : Form
    {
        private string purchaseNo;
        private int purchaseId;
        private List<Material> materials = new List<Material>();

        // 构造函数，接收采购编号
        public Revise(string purchaseNo)
        {
            InitializeComponent();
            this.purchaseNo = purchaseNo;
        }

        private void Revise_Load(object sender, EventArgs e)
        {
            
            // 初始化下拉框数据
            InitComboBoxData();
            // 加载采购申请数据
            LoadPurchaseData();
        }

        // 初始化下拉框数据
        // 修改审批人初始化代码
        private void InitComboBoxData()
        {
            materials = new List<Material>()
            {
                new Material { Id = "MAT001", Name = "黄豆" },
                new Material { Id = "MAT002", Name = "绿豆" },
                new Material { Id = "MAT003", Name = "红豆" },
                new Material { Id = "MAT004", Name = "黑豆" }
                // 可以根据实际需求添加更多原料
            };

            // 绑定原料下拉框
            comMatelal_name.DataSource = materials;
            comMatelal_name.DisplayMember = "Name";  // 显示名称
            comMatelal_name.ValueMember = "Id";      // 值成员
            comMatelal_name.SelectedIndex = -1;

            // 添加选择事件处理
            comMatelal_name.SelectedIndexChanged += ComMatelal_name_SelectedIndexChanged;

            // 初始化规格型号
            List<string> 规格型号 = new List<string>()
            {
                "次等豆", "中等豆", "上等豆", "特等豆"
            };
            comMatelal_Spec.DataSource = 规格型号;
            comMatelal_Spec.SelectedIndex = -1;

            // 初始化尺寸
            List<string> 尺寸 = new List<string>()
            {
                "4mm", "6mm", "8mm"
            };
            comMatelal_Dimension.DataSource = 尺寸;
            comMatelal_Dimension.SelectedIndex = -1;

            // 初始化审批人 - 使用对象列表包含ID和名称
            List<Approver> 审批人 = new List<Approver>()
            {
                new Approver { Id = 1, Name = "张三" },
                new Approver { Id = 2, Name = "王五" },
                new Approver { Id = 3, Name = "李四" }
            };
            comApprover_id.DataSource = 审批人;
            comApprover_id.DisplayMember = "Name";  // 显示名称
            comApprover_id.ValueMember = "Id";      // 值成员(ID)
            comApprover_id.SelectedIndex = -1;
        }
        private void ComMatelal_name_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comMatelal_name.SelectedIndex >= 0)
            {
                // 获取选中的原料
                Material selectedMaterial = (Material)comMatelal_name.SelectedItem;
                // 反填原料编号和名称
                textMaterlal_Id.Text = selectedMaterial.Id;
                comMatelal_name.Text = selectedMaterial.Name;
            }
            else
            {
                // 清空输入
                textMaterlal_Id.Text = "";
                comMatelal_name.Text = "";
            }
        }
        // 加载采购申请数据
        private async void LoadPurchaseData()
        {
            try
            {
                string apiUrl = $"http://10.223.8.9:8082/api/Purchase/GetPurchaseList?PageIndex=1&PageSize=1&Reqest_No={Uri.EscapeDataString(purchaseNo)}";
            
                using (HttpClient client = new HttpClient())
                {
                    // 设置请求头
                    client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                    client.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Charset", "utf-8");
                    client.Timeout = TimeSpan.FromSeconds(10);
                    
                    // 添加Token认证头
                    if (!string.IsNullOrEmpty(login.CurrentToken))
                    {
                        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", login.CurrentToken);
                    }
            
                    // 发送GET请求
                    HttpResponseMessage response = await client.GetAsync(apiUrl);
                    string jsonResponse = await response.Content.ReadAsStringAsync();
                    
                    // 添加调试信息：显示原始JSON响应
                    MessageBox.Show($"API响应: {jsonResponse}", "调试信息");
            
                    JObject jsonObject = JObject.Parse(jsonResponse);
            
                    // 修改数据解析部分
                    if (jsonObject["code"]?.Value<int>() == 200 && jsonObject["data"] != null)
                    {
                        // 获取data对象
                        JObject dataObject = jsonObject["data"] as JObject;
                        if (dataObject != null)
                        {
                            // 获取items数组
                            JArray itemsArray = dataObject["items"] as JArray;
                            if (itemsArray != null && itemsArray.Count > 0)
                            {
                                // 获取第一个元素
                                JObject firstItem = itemsArray[0] as JObject;
                                if (firstItem != null)
                                {
                                    WarehouseModel purchaseData = firstItem.ToObject<WarehouseModel>();
                                    if (purchaseData != null)
                                    {
                                        // 保存采购ID
                                        purchaseId = purchaseData.Id;
            
                                        // 填充表单数据
                                        textReqest_No.Text = purchaseData.Reqest_No;
                                        textMaterlal_Id.Text = purchaseData.Materlal_Id;
                                        // 从materials列表中查找匹配的原料
                                        var material = materials.FirstOrDefault(m => m.Name == purchaseData.Matelal_name);
                                        if (material != null)
                                        {
                                            comMatelal_name.SelectedItem = material;
                                        }
                                        comMatelal_name.Text = purchaseData.Matelal_name;
                                        numerRequest_Qty.Value = (decimal)purchaseData.Request_Qty;
                                        comMatelal_Spec.Text = purchaseData.Matelal_Spec;
                                        comMatelal_Dimension.Text = purchaseData.Matelal_Dimension + "mm";
            
                                        // 添加日期验证逻辑
                                        if (purchaseData.Request_Ddte > dateRequest_Ddte.MinDate && purchaseData.Request_Ddte < dateRequest_Ddte.MaxDate)
                                        {
                                            dateRequest_Ddte.Value = purchaseData.Request_Ddte;
                                        }
                                        else
                                        {
                                            // 设置为控件的最小日期或当前日期
                                            dateRequest_Ddte.Value = dateRequest_Ddte.MinDate;
                                        }
            
                                        textBudget_Amount.Text = purchaseData.Budget_Amount.ToString("F2");
                                        comApprover_id.Text = purchaseData.ApproverName;
                                        comBatch_No.Text= purchaseData.Batch_No;
                                    }
                                    else
                                    {
                                        MessageBox.Show("无法将JSON数据转换为WarehouseModel对象", "错误");
                                    }
                                }
                                else
                                {
                                    MessageBox.Show($"加载采购申请数据失败: {jsonObject["message"]?.Value<string>() ?? "未知错误"}", "错误");
                                }
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show($"加载采购申请数据失败: {jsonObject["message"]?.Value<string>() ?? "未知错误"}", "错误");
                    }
                }
            }
            catch (HttpRequestException ex)
            {
                // 处理Web异常
                string errorMessage = string.Empty;
                if (ex.Message.Contains("40"))
                {
                    errorMessage = "客户端错误: " + ex.Message;
                }
                else if (ex.Message.Contains("50"))
                {
                    errorMessage = "服务器错误: " + ex.Message;
                }
                else if (ex.Message.Contains("Connect"))
                {
                    errorMessage = "连接失败: 无法连接到服务器，请检查网络连接或服务器状态。";
                }
                else if (ex.Message.Contains("timeout"))
                {
                    errorMessage = "请求超时: 服务器响应超时，请稍后再试。";
                }
                else
                {
                    errorMessage = ex.Message;
                }
                MessageBox.Show($"加载数据失败: {errorMessage}");
            }
        }

        // 修改buttonSave_Click方法中的审批人数据
        private async void buttonSave_Click(object sender, EventArgs e)
        {
            // 验证表单数据
            if (string.IsNullOrEmpty(comMatelal_name.Text))
            {
                MessageBox.Show("请选择原料名称", "提示");
                return;
            }

            if (numerRequest_Qty.Value <= 0)
            {
                MessageBox.Show("采购数量必须大于0", "提示");
                return;
            }

            if (string.IsNullOrEmpty(textBudget_Amount.Text))
            {
                MessageBox.Show("请输入预算金额", "提示");
                return;
            }

            if (!decimal.TryParse(textBudget_Amount.Text, out decimal budgetAmount))
            {
                MessageBox.Show("预算金额格式不正确", "提示");
                return;
            }

            // 构造更新数据
            var updateData = new
            {
                Id = purchaseId,
                Reqest_No = textReqest_No.Text,
                Materlal_Id = textMaterlal_Id.Text,
                Matelal_name = comMatelal_name.Text,
                Request_Qty = (int)numerRequest_Qty.Value,
                Matelal_Spec = comMatelal_Spec.Text,
                Matelal_Dimension = comMatelal_Dimension.Text.Replace("mm", ""),
                Request_Ddte = dateRequest_Ddte.Value.ToString("yyyy-MM-dd"),
                Budget_Amount = budgetAmount,
                Approver_id = ((Approver)comApprover_id.SelectedItem).Id,
                Batch_No = comBatch_No.Text,  // 修改为获取文本值
                command = "UpdatePurchase"
            };

            try
            {
                string apiUrl = "http://10.223.8.9:8082/api/Purchase/UpdatePurchase";
                string jsonData = JsonConvert.SerializeObject(updateData);

                // 调试信息
                MessageBox.Show($"提交的数据: {jsonData}", "调试");

                using (HttpClient client = new HttpClient())
                {
                    // 设置请求头
                    client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                    client.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Charset", "utf-8");
                    client.Timeout = TimeSpan.FromSeconds(10);

                    // 添加Token认证头
                    if (!string.IsNullOrEmpty(login.CurrentToken))
                    {
                        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", login.CurrentToken);
                    }

                    // 创建请求内容
                    var content = new StringContent(jsonData, Encoding.UTF8, "application/json");

                    // 发送POST请求
                    HttpResponseMessage response = await client.PostAsync(apiUrl, content);
                    string jsonResponse = await response.Content.ReadAsStringAsync();
                    JObject jsonObject = JObject.Parse(jsonResponse);

                    if (jsonObject["code"]?.Value<int>() == 200)
                    {
                        MessageBox.Show("修改成功", "提示");
                        this.Close();
                        // 刷新采购列表
                        Purchaseshow purchaseshow = Application.OpenForms["Purchaseshow"] as Purchaseshow;
                        if (purchaseshow != null)
                        {
                            purchaseshow.RefreshData();
                        }
                    }
                    else
                    {
                        MessageBox.Show($"修改失败: {jsonObject["message"]?.Value<string>() ?? "未知错误"}", "错误");
                    }
                }
            }
            catch (HttpRequestException ex)
            {
                string errorMessage = "提交修改失败: ";
                if (ex.Message.Contains("40"))
                {
                    errorMessage += "客户端错误: " + ex.Message;
                }
                else if (ex.Message.Contains("50"))
                {
                    errorMessage += "服务器错误: " + ex.Message;
                }
                else if (ex.Message.Contains("Connect"))
                {
                    errorMessage += "连接失败: 无法连接到服务器，请检查网络连接或服务器状态。";
                }
                else if (ex.Message.Contains("timeout"))
                {
                    errorMessage += "请求超时: 服务器响应超时，请稍后再试。";
                }
                else
                {
                    errorMessage += ex.Message;
                }

                MessageBox.Show(errorMessage, "错误");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"发生错误: {ex.Message}", "错误");
            }
        }
        
        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }

    // 原料类
    public class Material
   {
      public string Id { get; set; }
        public string Name { get; set; }
    }
}